/**
 * 
 */
package com.ez.supervise.model.dto;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ez.supervise.model.sys.Permission;

/**
 * @author searph.wang
 * @email searph.wang@gmail.com
 * @Created at 2009-11-4
 * 
 */
public class Menu {
    
    public static String KEY_MENU = "menu";
    public static String ITEMS_EMPTY = "items : []";
    public static String MENU_TEMPLATE = "{id: 'supervise_menu', layout : 'accordion',region : 'center'," +
	    ITEMS_EMPTY + "}";
    public static String MAIN_MENU_TEMPLATE = "{id : '${menu.resId}-${menu.id}'," +
	    "title : \"<label class=\'font_menu_a\'>${menu.resName}</label>\"," + "border : false," +
	    "iconCls : 'icon-nav'," + ITEMS_EMPTY + "}";
    public static String SUB_MENU_TEMPLATE = "{id : '${menu.resId}_${menu.id}'," +
	    "title : \"<a href=javascript:createTab('${menu.panel}-${menu.id}') class='font_menu_b'>${menu.resName}</a>\"," +
	    "iconCls : 'icon-menu'," + "border : false," + ITEMS_EMPTY + "}";

    private Map<String, MainMenu> menus = new LinkedHashMap<String, MainMenu>();

    /**
     * @param permissions
     */
    public Menu(List<Permission> permissions) {
	List<Permission> mains = Permission.filter(permissions, Permission.TYPE_MAIN_MENU);
	// add main menu
	for (Permission permission : mains) {
	    MainMenu mainMenu = new MainMenu(permission);
	    List<Permission> children = Permission.children(permission, permissions);
	    if (!children.isEmpty()) {
		mainMenu.addSub(children);
	    }
	    menus.put(mainMenu.getKey(), mainMenu);
	}
    }

    public String toScript() {
	StringBuilder sb = new StringBuilder();
	String result;
	for (Iterator iterator = menus.values().iterator(); iterator.hasNext();) {
	    MainMenu main = (MainMenu) iterator.next();
	    sb.append(main.toScript() + ",");
	}
	if(sb.toString().endsWith(",")){
	    sb.deleteCharAt(sb.lastIndexOf(","));
	}
	result =  sb.toString();
	sb = new StringBuilder(MENU_TEMPLATE);
	int pos =  sb.lastIndexOf(Menu.ITEMS_EMPTY) + Menu.ITEMS_EMPTY.length() - 1;
	sb.insert(pos, result);
	return sb.toString();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
	// TODO Auto-generated method stub

    }

}
